Date.prototype.format = function (format) {
    var apd = function (i, v) {
        var str = (i + 100).toString();
        return str.substr(1, v == null ? 2 : Math.min(v, str.length - 1));
    };
    var d = {};
    d['yyyy'] = this.getFullYear();
    d['MM'] = apd(this.getMonth() + 1);
    d['dd'] = apd(this.getDate());
    d['HH'] = apd(this.getHours());
    d['mm'] = apd(this.getMinutes());
    d['ss'] = apd(this.getSeconds());
    for (var x in d) {
        format = format.replace(x, d[x]);
    }
    return format;
};
class EventTarget {
    constructor() {
        this.listeners = {};
    };
    addEventListener(type, callback) {
        if (!(type in this.listeners)) {
            this.listeners[type] = [];
        }
        this.listeners[type].push(callback);
    };

    removeEventListener(type, callback) {
        if (!(type in this.listeners)) {
            return;
        }
        var stack = this.listeners[type];
        for (var i = 0, l = stack.length; i < l; i++) {
            if (stack[i] === callback) {
                stack.splice(i, 1);
                return this.removeEventListener(type, callback);
            }
        }
    };

    dispatchEvent(event) {
        if (!(event.type in this.listeners)) {
            return;
        }
        var stack = this.listeners[event.type];
        event.target = this;
        for (var i = 0, l = stack.length; i < l; i++) {
            stack[i].call(this, event);
        }
    };
}
function getCaretPosition(ctrl) {
    // IE < 9 Support 
    if (document.selection) {
        ctrl.focus();
        var range = document.selection.createRange();
        var rangelen = range.text.length;
        range.moveStart('character', -ctrl.value.length);
        var start = range.text.length - rangelen;
        return {
            'start': start,
            'end': start + rangelen
        };
    } // IE >=9 and other browsers
    else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
        return {
            'start': ctrl.selectionStart,
            'end': ctrl.selectionEnd
        };
    } else {
        return {
            'start': 0,
            'end': 0
        };
    }
}

function setCaretPosition(ctrl, start, end) {
    // IE >= 9 and other browsers
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(start, end);
    }
    // IE < 9 
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', end);
        range.moveStart('character', start);
        range.select();
    }
}
var LoadingState = {
    Initial: 'INITIAL',
    Loading: 'LOADING',
    Success: 'SUCCESS',
    Failure: 'FAILURE',
}
var WarningBarState = {
    Initial: 'INITIAL',
    Failure: 'FAILURE',
    NotAllowedAsFirstMessage: 'NOT_ALLOWED_AS_FIRST_MESSAGE',
    FileTooBig: 'FILE_TOO_BIG',
    TooManyFiles: 'TOO_MANY_FILES',
    FilesWerentProcessed: 'FILES_WERENT_PROCESSED',
    BadExtension: 'BAD_EXTENSION',
    SameMessageTwice: 'SAME_MESSAGE_TWICE',
}
var FileUploadState = {
    Initial: 'INITIAL',
    Loading: 'LOADING',
}
var AgentRating = {
    Good: 5,
    Normal: 3,
    Bad: 1,
}
var WarningBarType = {
    Disconnect: 'DISCONNECT',
    UploadFailure: 'UPLOAD_FAILURE',
    FileRestricted: 'FILE_RESTRICTED',
    MessageRestricted: 'MESSAGE_RESTRICTED',
}
var enableSoundsStorageName = '_ss.enableSounds'
var hostWindow = window.parent
var currentWindow = window
var CHAT_ID_DATA_ATTR = 'data-smartsupp-id'

var initialSoundState = localStorage.getItem(enableSoundsStorageName);
function getFromStorage(name) {
    // Cookies
    var dataFromCookie = Cookie.get(cookieNameHelper(name))

    // Local storage
    var dataFromLocalStorage = getDataFromLocalStorage()
    var localDataItem = dataFromLocalStorage[name] ? dataFromLocalStorage[name] : undefined

    return dataFromCookie || localDataItem
}
var defaultConverter = {
    read: function (value) {
        return value.replace(/%3B/g, ';')
    },
    write: function (value) {
        return value.replace(/;/g, '%3B')
    },
}
Cookie = (function (converter, defaultAttributes) {
    function set(key, value, attributes) {
        if (typeof top.document === 'undefined') {
            return
        }

        attributes = assign({}, defaultAttributes, attributes)

        if (typeof attributes.expires === 'number') {
            attributes.expires = new Date(Date.now() + attributes.expires * 864e5)
        }
        if (attributes.expires) {
            attributes.expires = attributes.expires.toUTCString()
        }

        key = defaultConverter.write(key).replace(/=/g, '%3D')

        value = converter.write(String(value), key)

        let stringifiedAttributes = ''
        for (var attributeName in attributes) {
            if (!attributes[attributeName]) {
                continue
            }

            stringifiedAttributes += `; ${attributeName}`

            if (attributes[attributeName] === true) {
                continue
            }

            stringifiedAttributes += `=${attributes[attributeName].split(';')[0]}`
        }

        return (top.document.cookie = `${key}=${value}${stringifiedAttributes}`)
    }

    function get(key) {
        if (typeof top.document === 'undefined' || (arguments.length && !key)) {
            return
        }

        // To prevent the for loop in the first place assign an empty array
        // in case there are no cookies at all.
        var cookies = top.document.cookie ? top.document.cookie.split('; ') : []
        var jar = {}
        for (let i = 0; i < cookies.length; i++) {
            var parts = cookies[i].split('=')
            var value = parts.slice(1).join('=')
            var foundKey = defaultConverter.read(parts[0]).replace(/%3D/g, '=')
            jar[foundKey] = converter.read(value, foundKey)

            if (key === foundKey) {
                break
            }
        }

        return key ? jar[key] : jar
    }

    return Object.create(
        {
            set,
            get,
            remove(key, attributes) {
                set(
                    key,
                    '',
                    assign({}, attributes, {
                        expires: -1,
                    }),
                )
            },
            withAttributes(attributes) {
                return init(this.converter, assign({}, this.attributes, attributes))
            },
            withConverter(converter) {
                return init(assign({}, this.converter, converter), this.attributes)
            },
        },
        {
            attributes: { value: Object.freeze(defaultAttributes) },
            converter: { value: Object.freeze(converter) },
        },
    )
})(defaultConverter, { path: '/' });


var SS_COOKIE_PREFIX = 'ssupp'

// Special case for smartsupp homepage, where prefix is needed in order to prevent name clash
var cookieNamePrefix = getSsWidget().options.cookiePrefix ? getSsWidget().options.cookiePrefix : ''
var cookieNameHelper = (name) => `${cookieNamePrefix}${SS_COOKIE_PREFIX}.${name}`

var storageIdName = 'vid'
var storageVisitsName = 'visits'
var storageOpenName = 'opened'
var storageTextName = 'message'
var showWidgetButtonAnimationName = 'showButtonAnimation'
var defaultStorageIdExpirationInDays = 182
var LOCAL_STORAGE_OBJECT_NAME = `${SS_COOKIE_PREFIX}_${getSsWidget().options.key}`
var CRITICAL_COOKIES_LIST = [storageIdName, storageVisitsName]
var LOCAL_STORAGE_EXCEEDED_CODE = 22

var FALLBACK_PRIMARY_COLOR = '#1233df'
var BUTTONS_DARKEN_MULTIPLIER = 0.3
var INPUT_BORDER_DARKEN_MULTIPLIER = 0.3
var BUTTONS_HOVER_MULTIPLIER = 0.9
var OLD_BLUE_HEX = '#3598DC'
var NEW_BLUE_HEX = '#134AD2'
var SSPX = 8
// Is here separately in a function in order to be able to reset cookies and localStorage, if it was not a function it would not be possible
function getDataFromLocalStorage() {
    return JSON.parse(localStorage.getItem(LOCAL_STORAGE_OBJECT_NAME) || '{}')
}
function getFromStorage(name) {
    // Cookies
    var dataFromCookie = Cookie.get(cookieNameHelper(name))

    // Local storage
    var dataFromLocalStorage = getDataFromLocalStorage()
    var localDataItem = dataFromLocalStorage[name] ? dataFromLocalStorage[name] : undefined

    return dataFromCookie || localDataItem
}
var initialState = {
    currentTriggerMessageId: undefined,
    messages: [],
    enableSounds: getInitSoundsState(),
    emojiPickerState: false,
    inputText: getFromStorage(storageTextName) || '',
    isTyping: false,
    fakeTyping: false,
    warningBarState: WarningBarState.Initial,
    fileUploadState: FileUploadState.Initial,
    lastReadAt: null,
    messageSendingState: LoadingState.Initial,
    acceptedFileTypes: [],
    acceptedFileExtensions: [],
    acceptedFileMaxSize: 0,
}
function getInitSoundsState() {
    if (initialSoundState) {
        return initialSoundState === 'true'
    }
    if (getSsWidget().options.enableSounds !== undefined) {
        return getSsWidget().options.enableSounds
    }
    if (getSsWidget().options.soundMuted !== undefined) {
        // This is legacy option
        return !getSsWidget().options.soundMuted
    }
    return true
}
function getSsLoader() {
    if (hostWindow.$smartsupp) {
        return hostWindow.$smartsupp
    }
    return { getChat: () => undefined, on: () => undefined, fire: () => undefined }
}
function getSsWidget() {
    if (currentWindow.$smartsuppTest) {
        var testOptions = currentWindow.$smartsuppTest
        return mapSsOptions(testOptions)
    }
    if (hostWindow.$smartsupp) {
        var bodyEl = document.getElementsByTagName('body')[0]
        var chatId = bodyEl.getAttribute(CHAT_ID_DATA_ATTR)

        if (!chatId) throw new Error(`Missing attribute "${CHAT_ID_DATA_ATTR}" on body element.`)

        return mapSsOptions(getSsLoader().getChat(chatId))
    }
    return {
        options: {},
        installApi: () => undefined,
        getBaseUrl: () => '',
    }
}

function mapSsOptions(widget) {
    var { installApi, getBaseUrl, ...rest } = widget
    var idealOptions = {
        ...rest,
        options: {
            ...rest.options,
            orientation: rest.options.alignX || rest.options.orientation || ChatOrientation.Right,
            cookieDomain: rest.options.cookieDomain || '',
            cookiePath: rest.options.cookiePath || '/',
            color: rest.options.features.customize ? rest.options.color : FALLBACK_PRIMARY_COLOR,
            hideWidget: rest.options.features.customize ? rest.options.hideWidget : false,
            hideOfflineChat: rest.options.features.customize ? rest.options.hideOfflineChat : false,
            numberControl: rest.options.features.customize ? rest.options.numberControl : false,
            privacyNoticeEnabled: rest.options.features.customize ? rest.options.privacyNoticeEnabled : false,
            privacyNoticeCheckRequired: rest.options.features.customize ? rest.options.privacyNoticeCheckRequired : false,
            requireLogin: rest.options.features.customize ? rest.options.requireLogin : false,
            ratingEnabled: rest.options.features.rating ? rest.options.ratingEnabled : false,
            transcriptEnabled: false,
            groupSelectEnabled: rest.options.features.groups ? rest.options.groupSelectEnabled : false,
            offsetX: rest.options.offsetX,
            offsetY: rest.options.offsetY,
            buttonStyle: rest.options.buttonStyle || ButtonStyle.Greeting,
        },
        installApi: installApi.bind(widget),
        getBaseUrl: getBaseUrl.bind(widget),
    }
    return idealOptions
}
window.widget = new class extends EventTarget {
    constructor() {
        super();
        this.is_mobile = navigator.userAgent.toLowerCase().indexOf('mobile') != -1;
        this.entry_button_url = this.is_mobile ? `//${location.host}/app.m.iframe.html`
            : `//${location.host}/widget.entrybutton.html`;
        this.chat_widget_url = this.is_mobile ? `//${location.host}/app.m.iframe.html`
            : `//${location.host}/widget.chatwindow.html`;
        this.isChatOpen = false;
        this.handlerInstalled = false;
        this.controls = {}
        this.tpls = {
            textmsg: '<div class="message-list" data-cy="messageList"><div class="css-1m5mtjz"><div class="MuiGrid-root MuiGrid-container MuiGrid-justify-xs-flex-end"><div class="MuiGrid-root css-m89s7i MuiGrid-container MuiGrid-justify-xs-flex-end"><div class="text-message css-1iymmi9" data-cy="textMessage"></div><div class="MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12"></div></div></div></div></div>',
            msgtime: '<div class="MuiGrid-root MuiGrid-container MuiGrid-justify-xs-flex-end"><span class="css-4t4fby"> 51 minutes ago </span></div>',
            soundsOn: '<svg viewBox="0 0 24 24" role="presentation" class="css-1csy9g" style="width: 1.5rem; height: 1.5rem;"><path d="M21,19V20H3V19L5,17V11C5,7.9 7.03,5.17 10,4.29C10,4.19 10,4.1 10,4A2,2 0 0,1 12,2A2,2 0 0,1 14,4C14,4.1 14,4.19 14,4.29C16.97,5.17 19,7.9 19,11V17L21,19M14,21A2,2 0 0,1 12,23A2,2 0 0,1 10,21M19.75,3.19L18.33,4.61C20.04,6.3 21,8.6 21,11H23C23,8.07 21.84,5.25 19.75,3.19M1,11H3C3,8.6 3.96,6.3 5.67,4.61L4.25,3.19C2.16,5.25 1,8.07 1,11Z" style="fill: currentcolor;"></path></svg>',
            soundsOff: '<svg viewBox="0 0 24 24" role="presentation" class="css-1csy9g" style="width: 1.5rem; height: 1.5rem;"><path d="M20.84,22.73L18.11,20H3V19L5,17V11C5,9.86 5.29,8.73 5.83,7.72L1.11,3L2.39,1.73L22.11,21.46L20.84,22.73M19,15.8V11C19,7.9 16.97,5.17 14,4.29C14,4.19 14,4.1 14,4A2,2 0 0,0 12,2A2,2 0 0,0 10,4C10,4.1 10,4.19 10,4.29C9.39,4.47 8.8,4.74 8.26,5.09L19,15.8M12,23A2,2 0 0,0 14,21H10A2,2 0 0,0 12,23Z" style="fill: currentcolor;"></path></svg>'
        }
        this.chat = parent.$smartsupp.widgets.chat;
        this.request = parent.installedModules[2].exports.request;
    }
    on(eventName, handler) {
        this.addEventListener(eventName, handler);
    }

    setupChatButton() {
        this.request(this.entry_button_url + '?t=' + new Date().getTime())
            .then((d) => this.onChatButtonLoad(d));
    }
    onChatButtonLoad(d) {
        document.body.innerHTML = d;
        //background: transparent; overflow: hidden; display: block; margin: 0px; padding: 0px; bottom: 1px; transition: none 0s ease 0s; z-index: 10000001; position: fixed; width: 1px; height: 1px; right: 1px;
        //background: transparent; overflow: hidden; display: block; margin: 0px; padding: 0px; bottom: 1px; transition: none 0s ease 0s; z-index: 10000001; position: fixed; width: 0px; height: 0px; right: 1px; max-height: 0px; max-width: 0px;
        //background: transparent; overflow: hidden; display: block; margin: 0px; padding: 0px; bottom: 24px; transition: none 0s ease 0s; z-index: 2147483647; position: fixed; width: 112px; height: 56px; right: 11px; max-height: 56px; max-width: 112px; box-sizing: border-box;
        widget.chat.el.style =
            'background: transparent; overflow: hidden; display: block; margin: 0px; padding: 0px; bottom: 24px; transition: none 0s ease 0s; z-index: 2147483647; position: fixed; width: 112px; height: 56px; right: 11px; max-height: 56px; max-width: 112px; box-sizing: border-box;'
        this.isChatOpen = false;
        if (!this.handlerInstalled) {
            document.addEventListener('click', () => this.openChatWidget());
            this.handlerInstalled = true;
        }
        this.dispatchEvent({ type: 'chatClose' })
    }
    onChatWidgetLoad(d) {
        document.body.innerHTML = d;
        this.chat.el.style = 'background: transparent; overflow: hidden; display: block; margin: 0px; padding: 0px; bottom: 24px; transition: none 0s ease 0s; z-index: 2147483647; position: fixed; width: 366px; height: calc(100vh - 36px); right: 11px; max-height: 600px; max-width: 366px; box-sizing: border-box;';
        this.setupChatWidget();
        this.isChatOpen = 1;
        super.dispatchEvent({ type: "chatOpen" });
    }
    openChatWidget() {
        if (this.isChatOpen)
            return;
        console.log('openChatWidget')
        this.request(widget.chat_widget_url + '?t=' + new Date().getTime())
            .then((d) => this.onChatWidgetLoad(d));

    };

    resetStyle() {
        this.controls.elm_emoji.style.display = 'none';
        this.controls.element_options.style.display = 'none';

    }
    resetInput() {
        this.controls.elm_input.value = '';
        this.controls.btn_files.style.display = 'block';
        this.controls.btn_sendm.style.display = 'none';
    }
    onEmojiClick(e) {
        e.stopPropagation();
    }
    onMenusClick(e) {
        e.stopPropagation();
    }
    onInputFocus(e) {
        if (e.type == 'focus') {
            this.controls.elm_bluel.classList.remove('css-1sne0cn');
        }
        else {
            this.controls.elm_bluel.classList.add('css-1sne0cn');
        }
    }
    insertSendText(str) {
        var textObj = this.controls.elm_input;
        if (textObj.setSelectionRange) {
            var rangeStart = textObj.selectionStart;
            var rangeEnd = textObj.selectionEnd;
            var tempStr1 = textObj.value.substring(0, rangeStart);
            var tempStr2 = textObj.value.substring(rangeEnd);
            textObj.value = tempStr1 + str + tempStr2;
            rangeStart = rangeStart + str.length;
            setCaretPosition(textObj, rangeStart, rangeStart);
            this.checkInput(1);
        } else {
            alert("This version of Mozilla based browser does not support setSelectionRange");
        }
    }

    onEmojiItemClick(e) {
        var emoji = e.target.getAttribute('alt');
        this.insertSendText(emoji);
        this.resetStyle();
    }

    doSend(text) {
        //this.appendMessage({ type: 'text', content: text });
        console.log('doSend');
        this.controls.elm_input.value = '';
        this.checkInput(0);
        this.dispatchEvent({ type: 'send', content: text });
    };

    updateSoundStatus(status) {
        this.isSoundOpen = status;
        var item = document.createRange().createContextualFragment(status ? this.tpls.soundsOn : this.tpls.soundsOff).firstChild;
        this.controls.btn_toggleNotification.firstChild.remove();
        this.controls.btn_toggleNotification.prepend(item);
        this.controls.btn_toggleNotification.querySelector('.css-ka2v1h').innerText = status ? '关闭消息提示音' : '打开消息提示音';
    }

    createMessageList(msg) {
        var item = document.createRange().createContextualFragment(this.tpls.textmsg).firstChild;
        item.querySelector('.text-message').innerText = msg.content;
        var time = document.createRange().createContextualFragment(this.tpls.msgtime).firstChild;
        item.querySelector('.text-message').parentElement.appendChild(time);

        var sendDate = new Date(msg.sendTime);
        var currDate = new Date();
        var timeText = sendDate.format('yyMMddHH') != currDate.format('yyMMddHH') ? sendDate.format('MM-dd HH:mm') : sendDate.format('HH:mm');
        time.querySelector('span').innerText = timeText;
        //访客css-m89s7i
        //客服css-sq693j
        if (msg.sendby == 'agent') {
            //访客发的在右边，客服发的在左边
            item
                .querySelectorAll('.MuiGrid-container')
                .forEach(function (x) {
                    x.classList.remove('css-m89s7i')
                    x.classList.add('css-sq693j')
                    x.classList.remove('MuiGrid-justify-xs-flex-end');
                });
        }
        else {
            item
                .querySelectorAll('.MuiGrid-container')
                .forEach(function (x) {
                    x.classList.remove('css-sq693j')
                    x.classList.add('css-m89s7i')
                    x.classList.add('MuiGrid-justify-xs-flex-end');
                });
        }
        return item;
    }
    appendMessage(msg) {
        var container = document.querySelector('.css-15on28x');
        if (msg.type = 'text') {
            var item = this.createMessageList(msg);
            container.appendChild(item);
            item.scrollIntoView();
        }

    }
    beautifyMessageDisplay() {
        //TODO 
    }
    checkInput(hasText) {
        if (hasText) {
            // 显示发送按钮
            this.controls.btn_sendm.style.display = 'block';
            this.controls.btn_files.style.display = 'none';
        }
        else {
            // 显示文件选择按钮
            this.controls.btn_files.style.display = 'block';
            this.controls.btn_sendm.style.display = 'none';
        }
        console.log('hasText:' + hasText);
    };

    onInputChange(e) {
        this.checkInput(e.target.value.length > 0);
    };

    onSendClick() {
        var target = this.controls.elm_input;
        this.doSend(target.value);
    }
    toggleNotification(e) {
        console.log('toggleNotification');
        this.updateSoundStatus(!this.isSoundOpen);
        this.resetStyle();
    }
    onInputKeydown(e) {
        if (this.preventEnter(e) && e.target.value.length > 0) {
            this.doSend(e.target.value);
        }
    }
    onCloseClick() {
        console.log("closeChatWidget");
        this.setupChatButton();
    }
    preventEnter(e) {
        var et = e || window.event;
        var keycode = et.charCode || et.keyCode;
        if (keycode == 13) {
            if (window.event) {
                window.event.returnValue = false;
            } else {
                e.preventDefault();
            }
            return true;
        }
    };
    onSessionReady(m) {
        this.visitor = m.from;
    };
    onAgentMessage(m) {
        var sendby = 'agent';
        if (m.from && m.from.userId == this.visitor.userId) {
            sendby = 'visitor';
        }
        if(m.sendBy=='visitor'){
            sendby='visitor';
        }
        this.appendMessage({
            sendby: sendby,
            type: 'text', content: m.content,
            sendTime: m.sendTime
        });
    }
    onAgentSched(m) {
        //调度客服
    }
    setupChatWidget() {
        this.controls.btn_close = document.querySelector('[data-cy="mobileCloseButton"]');
        this.controls.btn_files = document.querySelector('[data-cy="addFileIconButton"]');
        this.controls.btn_sendm = document.querySelector('[data-cy="sendIconButton"]');
        this.controls.btn_emoji = document.getElementById("open-emoji-button");
        this.controls.elm_emoji = document.getElementById("emoji-selector");
        this.controls.btn_moreOptions = document.querySelector("[data-cy=moreOptionsButton]");
        this.controls.element_options = document.querySelector("[role=tooltip]");
        this.controls.elm_input = document.getElementById("chatInput");
        this.controls.elm_bluel = document.getElementsByClassName('css-1sne0cm')[0];
        this.controls.btn_toggleNotification = document.querySelector('[data-cy=toggleNotificationsButton]');
        this.controls.elm_emoji_items = document.querySelector('[data-cy="emojiPicker"]').getElementsByClassName('emoji');
        for (let index = 0; index < this.controls.elm_emoji_items.length; index++) {
            var element = this.controls.elm_emoji_items[index];
            element.onclick = (e) => this.onEmojiItemClick(e);
        }
        var that = this;
        this.controls.btn_emoji.onclick = function (e) {
            that.controls.elm_emoji.style.display = 'block';
            e.stopPropagation();
        }
        this.controls.btn_moreOptions.onclick = function (e) {
            that.controls.element_options.style.display = 'block';
            e.stopPropagation();
        }
        this.controls.btn_toggleNotification.onclick = (e) => this.toggleNotification(e);
        this.controls.btn_sendm.onclick = (e) => this.onSendClick(e);
        this.controls.elm_input.onkeyup = (e) => this.onInputChange(e);
        this.controls.elm_input.onchange = (e) => this.onInputChange(e);
        this.controls.elm_input.onkeydown = (e) => this.onInputKeydown(e);
        this.controls.elm_input.onfocus = (e) => this.onInputFocus(e);
        this.controls.elm_input.onblur = (e) => this.onInputFocus(e);
        this.controls.elm_emoji.onclick = (e) => this.onEmojiClick(e);
        this.controls.element_options.onclick = (e) => this.onMenusClick(e);
        this.controls.btn_close.onclick = (e) => this.onCloseClick(e);
        document.addEventListener("click", (e) => this.resetStyle(e));

        this.resetStyle();
        this.resetInput();
    }
}();
widget.setupChatButton();

//===========================client====================================//
function agent() {
    var c = function () {
        this.id = 0;
        this.name = '';
    }
    c.prototype.update = function (agent) {
        this.id = agent.id;
        this.name = agent.name;
    }
}

function waitSocketIOReady() {
    if (window.io == undefined) {
        setTimeout(() => {
            waitSocketIOReady();
        }, 100);
    }
    else {
        window.socketClient = new class socketClient {
            constructor(widget) {
                this.widget = widget;
                this.socket = null;
                this.widget.on('chatOpen', () => this.initialize());
                this.widget.on('chatClose', () => this.dispose());
                this.widget.on('send', (e) => this.doSend(e));
                this.messages = [];
                this.sessionReady = false;
            }
            doSend(e) {
                this.socket.emit('chat message', e.content);
            };
            doUpload() { };
            render(msg) {
                if (this.sessionReady) {
                    while (this.messages.length > 0) {
                        var m = this.messages.shift();
                        this.widget.onAgentMessage(m);
                    }
                    this.widget.onAgentMessage(msg);
                }
                else {
                    this.messages.push(msg);
                }
            }
            initialize() {
                this.socket = io('127.0.0.1:9000')
                this.socket.on('chat message', (d) => this.onMessage(d));
            }
            dispose() {
                this.socket && this.socket.disconnect();
            }
            onMessage(d) {
                var m = {};
                try {
                    m = JSON.parse(d);
                    console.log(m);
                } catch{

                }
                if (m.typeName == 'SESSION_READY') {//1
                    this.widget.onSessionReady(m);
                    this.sessionReady = true;
                }
                else {
                    if (m.typeName == 'SYSTEM') {//0
                        m.content = '系统消息：' + m.content;
                        this.render(m);
                    }
                    else if(m.typeName=="CHAT_HISTORY"){
                        for (let i = 0; i < m.content.length; i++) {
                            const element = m.content[i];
                            this.render(element)
                        }
                    }
                    else if (m.typeName == 'PRIVATE_CHAT') {
                        this.render(m);
                    }
                    else if (m.typeName == 'GROUP_CHAT') {//100
                        m.content = m.from.nickName + '：' + m.content;
                        this.render(m);
                    }
                    else if (m.typeName == "BUDDY_ENTER") {//4
                        m.content_bk = m.content;
                        m.content = '系统消息：' + m.from.nickName + ' 加入聊天, 当前' + m.content.numberOfOnlineUsers + '人在线';
                        m.from = null;
                        this.render(m);
                    }
                    else if (m.typeName == 'BUDDY_LEAVE') {
                        m.content_bk = m.content;
                        m.content = '系统消息：' + m.from.nickName + ' 离开聊天, 当前' + m.content.numberOfOnlineUsers + '人在线';
                        m.from = null;
                        this.render(m);
                    }
                    else if (m.typeName == 'AGENT_SCHED') {
                        this.widget.onAgentSched(m);
                    }
                    else {
                        console.log('unknown msg type');
                    }
                }
            }
        }(window.widget);
    }
}
waitSocketIOReady();
